package com.missmess.opengldemo.ui;

import android.os.Bundle;

import com.missmess.opengldemo.GlBaseActivity;
import com.missmess.opengldemo.util.BufferUtils;

import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

public class DrawPolyhedron extends GlBaseActivity {
    final float X = .525731112119133606f;
    final float Z = .850650808352039932f;
    float vertices[] = new float[]{
            -X, 0.0f, Z,
            X, 0.0f, Z,
            -X, 0.0f, -Z,
            X, 0.0f, -Z,
            0.0f, Z, X,
            0.0f, Z, -X,
            0.0f, -Z, X,
            0.0f, -Z, -X,
            Z, X, 0.0f,
            -Z, X, 0.0f,
            Z, -X, 0.0f,
            -Z, -X, 0.0f
    };

    short indices[] = new short[]{
            0, 4, 1, 0, 9, 4, 9, 5, 4, 4, 5, 8, 4, 8, 1,
            8, 10, 1, 8, 3, 10, 5, 3, 8, 5, 2, 3, 2, 7, 3,
            7, 10, 3, 7, 6, 10, 7, 11, 6, 11, 0, 6, 0, 1, 6,
            6, 1, 10, 9, 0, 11, 9, 11, 2, 9, 2, 5, 7, 2, 11};

    float[] colors = {
            0f, 0f, 0f, 1f,
            0f, 0f, 1f, 1f,
            0f, 1f, 0f, 1f,
            0f, 1f, 1f, 1f,
            1f, 0f, 0f, 1f,
            1f, 0f, 1f, 1f,
            1f, 1f, 0f, 1f,
            1f, 1f, 1f, 1f,
            1f, 0f, 0f, 1f,
            0f, 1f, 0f, 1f,
            0f, 0f, 1f, 1f,
            1f, 0f, 1f, 1f

    };

    private FloatBuffer vb;
    private ShortBuffer sb;
    private FloatBuffer cvb;
    private int angle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = BufferUtils.float2Buffer(vertices);
        sb = BufferUtils.short2Buffer(indices);
        cvb = BufferUtils.float2Buffer(colors);
    }

    @Override
    public void drawScene(GL10 gl) {
        super.drawScene(gl);
        onlyCCW(gl);
        gl.glTranslatef(0, 0, -4f);

        gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
        gl.glRotatef(angle, 0, 1, 0);

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_COLOR_ARRAY);

        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vb);
        gl.glColorPointer(4, GL10.GL_FLOAT, 0, cvb);
        gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,
                GL10.GL_UNSIGNED_SHORT, sb);

        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_COLOR_ARRAY);

        angle++;
    }
}
